package com.woniuxy.cloud.batteryassembly.service.impl;

import cn.hutool.core.lang.generator.SnowflakeGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.cloud.batteryassembly.dto.PageBatteryDto;
import com.woniuxy.cloud.batteryassembly.esrepo.BatteryRepo;
import com.woniuxy.cloud.batteryassembly.exception.BatteryInfoException;
import com.woniuxy.cloud.batteryassembly.mapper.BatteryMapper;
import com.woniuxy.cloud.batteryassembly.model.Battery;
import com.woniuxy.cloud.batteryassembly.service.IBatteryService;
import com.woniuxy.cloud.batteryassembly.service.IBatteryTypeService;
import com.woniuxy.cloud.batteryassembly.util.WoniuBeanUtils;
import com.woniuxy.cloud.dto.BatteryDto;
import com.woniuxy.cloud.dto.BatteryTypeDto;
import com.woniuxy.cloud.dto.QueryBatteryDto;
import com.woniuxy.cloud.param.*;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author gaorui
 * @since 2022-02-09
 */
@Service
@Slf4j
public class BatteryServiceImpl extends ServiceImpl<BatteryMapper, Battery> implements IBatteryService {

    @Resource
    private IBatteryTypeService service;


    //根据ID查询电池信息并判断该电池是否可用
    @GlobalTransactional
    @Override
    public Battery findById(Integer id) {
        Battery battery = getById(id);
        if (battery == null) throw new BatteryInfoException("查询失败，没有该电池信息", 1001);

        if (battery.getDamageLevel().equals("高级")) {
            battery.setBatteryStatus(1);
            int i = baseMapper.updateById(battery);
            if (i <= 0) throw new BatteryInfoException("修改失败,请稍后再试", 3002);
        }


        return battery;
    }

    //根据网点查询电池信息
    @Override
    public PageBatteryDto listBattery(ListBatteryParam listBatteryParam) {
        QueryWrapper<Battery> queryWrapper = new QueryWrapper<>();

//        if (null != listBatteryParam.getKeyword()) {
//            queryWrapper.and(qw -> {
//                //电池状态
//                qw.like("battery_status", listBatteryParam.getKeyword());
//            });
//        }
//        //判断状态是否为空
//        if (!StringUtils.isEmpty(listBatteryParam.getBatteryStatus())) {
//            queryWrapper.eq("battery_status", listBatteryParam.getBatteryStatus());
//        }

        //  Battery battery = this.baseMapper.selectById(listBatteryParam.getLocationId());
        //根据网点ID查询出电池信息
//        List<Battery> batteryList = list(new QueryWrapper<Battery>().in("location_id", listBatteryParam.getLocationId()));
//
//
//        List<Battery> stream = batteryList.stream().filter(
//                element -> "高级".equals(element.getDamageLevel())
//        ).collect(Collectors.toList());

        // queryWrapper=   new QueryWrapper<Battery>().in("location_id", listBatteryParam.getLocationId()).ne("damage_level","高级");

        //sql语句 查询出电池信息
        List<QueryBatteryDto> pageBatteryDto1 = this.baseMapper.listBattery(listBatteryParam);

//        IPage<Battery> iPage = page(new Page<>(listBatteryParam.getIndexPage(), listBatteryParam.getPageSize()), queryWrapper);
//
        PageBatteryDto pageBatteryDto = new PageBatteryDto();

        pageBatteryDto.setIndexPage(listBatteryParam.getIndexPage());//设置当前页

        String s = String.valueOf(pageBatteryDto1.size());

        pageBatteryDto.setTotal(Long.valueOf(s));//设置总条数

        ArrayList<QueryBatteryDto> arrayList = new ArrayList<>();

        Long indexNum = (listBatteryParam.getIndexPage() - 1) * listBatteryParam.getPageSize();


        for (int i = 0; i < pageBatteryDto1.size(); i++) {
            if (i >= indexNum && i < indexNum + listBatteryParam.getPageSize()) {
                arrayList.add(pageBatteryDto1.get(i));
            }
        }
        pageBatteryDto.setBatteryDtoList(arrayList);//装入当前页的dto数据

//        //获取当前页
//        pageBatteryDto.setIndexPage(iPage.getCurrent());
//        //当前满足条件总行数
//        pageBatteryDto.setTotal(iPage.getTotal());
//
//        pageBatteryDto.setBatteryDtoList(WoniuBeanUtils.copyList(iPage.getRecords(), BatteryDto.class));
        if (indexNum < listBatteryParam.getPageSize()) {
            pageBatteryDto.setHasPrevious(false);//没有上一页
        } else {
            pageBatteryDto.setHasPrevious(true);//有上一页
        }
        Long indexMax = (listBatteryParam.getIndexPage()) * listBatteryParam.getPageSize() - 1;
        if (indexMax < pageBatteryDto1.size()) {
            pageBatteryDto.setHasNext(true);//有下一页
        } else {
            pageBatteryDto.setHasNext(false);//没有下一页
        }
        return pageBatteryDto;
    }

    @Override
    public List<BatteryDto> batteriesIsHealth(BatteriesIsHealthParam param) {
//        QueryWrapper<Battery> queryWrapper = new QueryWrapper<>();
//        queryWrapper.gt("battery_electricity",90)
//                .eq("battery_status",0)
//                .eq("battery_del",0)
//                .eq("battery_location_level",1)
//                .eq("location_id",OneBatteryParam.getBranchesId())
//                .in("battery_id",OneBatteryParam.getBatteriesId());
//        List<Battery> list = list(queryWrapper);
//        System.out.println(list);
//        List<BatteryDto> batteryDtos = WoniuBeanUtils.copyList(list, BatteryDto.class);
        //获取到电池信息
        Battery battery = getById(param.getBatteriesId().get(0));
        //判断是否查到信息
        if (battery == null) return null;
        //如果查询到 把电池ID设为网点ID
        param.setBranchesId(battery.getLocationId());
        //返回xml中sql查询结果
        return this.baseMapper.batteriesIsHealth(param);
    }

    @Override//根据ID批量查询电池信息
    public List<Battery> findBatteryByIds(@RequestBody List<Integer> ids) {

        List<Battery> batteries = baseMapper.selectBatchIds(ids);

        return batteries;
    }

    @Override//添加电池信息
    public Boolean addBattery(BatteryParam batteryParam) {
        //雪花计算法自动生成编号
        Long next = new SnowflakeGenerator().next();
        String code = "bat" + next.toString();

        Battery entity = WoniuBeanUtils.copyObject(batteryParam, Battery.class);
        //把自动生成的编号设置到添加信息中
        entity.setBatteryCode(code);
        //添加到数据库
        boolean save = save(entity);

        return save;
    }

    @Transactional
    @Override//删除电池信息
    public Boolean deleteBattery(List<Integer> batteryIds) {

        List<Battery> batteryList = list(new QueryWrapper<Battery>().in("battery_id", batteryIds));
        if (null == batteryList || batteryList.size() <= 0)
            throw new BatteryInfoException("删除失败，删除内容不能为空", 1005);

        //过滤掉不符合删除条件的数据
        List<Battery> collect = batteryList.stream().filter(battery -> {
            Boolean flag = !(battery.getBatteryDel() == 1);
            //逻辑删除
            if (flag) battery.setBatteryDel(1);
            return flag;
        }).collect(Collectors.toList());//将符合删除条件的数据添加到新集合内
        if (collect.size() != batteryList.size())
            throw new BatteryInfoException("删除失败,有条件不满足", 1006);
        return updateBatchById(collect);

    }


    @GlobalTransactional
    @Override
    public Boolean updateBattery(BatteryParam batteryParam) {
        Battery battery = WoniuBeanUtils.copyObject(batteryParam, Battery.class);
        //直接根据ID修改
        int update = baseMapper.updateById(battery);
        if (update > 0) {
            findById(batteryParam.getBatteryId());
            return true;
        }

        throw new BatteryInfoException("修改失败", 1004);
    }

    @Override
    public Boolean updateBattery(UpdateParam updateParam) {

        QueryWrapper<Battery> qw = new QueryWrapper<>();
        qw.in("battery_code", updateParam.getBatteryCodes());
        qw.eq("battery_status", 0).eq("battery_del", 0);

        List<Battery> batteries = baseMapper.selectList(qw);

        if (batteries.size() <= 0) {
            throw new BatteryInfoException("当前电池不存在或不可用", 20002);
        }

        for (Battery battery : batteries) {
            battery.setLocationId(updateParam.getLocationId());
            //设置位置地点
            battery.setBatteryLocation(updateParam.getBatteryLocation());

            battery.setBatteryLocationLevel(updateParam.getLocationLevel());
        }
        boolean b = this.updateBatchById(batteries);
        if (b) return true;
        throw new BatteryInfoException("修改失败", 1004);
    }

    @GlobalTransactional
    @Override//根据电池对象集合修改
    public Boolean updateList(UpdateListParam updateListParam) {
        //把电池ID过滤组成一个新集合
        List<Integer> collect = updateListParam.getParamList().stream().map(para -> para.getBatteryId()).collect(Collectors.toList());
        //根据ID直接找出电池信息
        List<Battery> batteries = listByIds(collect);
        //判断修改信息是否正确
        if (batteries == null || batteries.size() == 0 || batteries.size() != updateListParam.getParamList().size()) {
            throw new BatteryInfoException("传入信息异常", 20003);
        }
        for (int i = 0; i < batteries.size(); i++) {
            for (int j = 0; j < updateListParam.getParamList().size(); j++) {
                //判断传入信息和要修改信息是否对应
                if (batteries.get(i).getBatteryId() ==
                        updateListParam.getParamList().get(j).getBatteryId()) {
                    //设置电量
                    batteries.get(i).setBatteryElectricity(updateListParam.getParamList().get(j).getBatteryElectricity());
                    //损坏ID
                    batteries.get(i).setDamageId(updateListParam.getParamList().get(j).getDamageId());
                    //损坏等级
                    batteries.get(i).setDamageLevel(updateListParam.getParamList().get(j).getDamageLevel());
                    //获取到损坏ID
                    Integer damageId = updateListParam.getParamList().get(j).getDamageId();
                    //3,4,6为损坏等级高级
                    if (damageId == 4 || damageId == 3 || damageId == 6) {
                        //设置为不可用
                        batteries.get(i).setBatteryStatus(1);
                    }
                }
            }
        }
        if (updateBatchById(batteries)) {
//            List<UpdateBatteryDto> updateBatteryDtos = WoniuBeanUtils.copyList(updateListParam.getParamList(), UpdateBatteryDto.class);
            return true;
        } else {
            throw new BatteryInfoException("修改失败", 20003);
        }
    }

    @Override//批量添加电池信息
    public Boolean addBatteryList(AddListBatteryParam addListBatteryParam) {
        //获取到要添加电池集合
        List<SaveBatteryParam> batteryParams = addListBatteryParam.getBatteryParams();

        System.out.println(addListBatteryParam);

        List<Integer> list = batteryParams.stream().distinct().map(id -> id.getBatteryTypeId()).collect(Collectors.toList());
        //去重
        List<Integer> myList = list.stream().distinct().collect(Collectors.toList());
        //根据电池类型查询出电池
        List<BatteryTypeDto> batteryType = service.findBatteryType(myList);
        if (batteryType.size() != myList.size()) throw new BatteryInfoException("添加电池类型有误，请检查数据", 20004);
        //把要添加的信息 集合映射到实体
        List<Battery> batteries = WoniuBeanUtils.copyList(batteryParams, Battery.class);
        //遍历循环   设置默认值
        for (Battery battery : batteries) {
            battery.setBatteryElectricity(100);
            battery.setDamageId(7);
            battery.setDamageLevel("无");
            battery.setBatteryStatus(0);
            battery.setBatteryDel(0);
        }

        return saveBatch(batteries);
    }

    @Override
    public List<BatteryDto> listBatteryByLocationIdAndTypeId(Integer locationId, Integer typeId) {
        List<Battery> list = list(new QueryWrapper<Battery>().eq("location_id", locationId).eq("battery_type_id", typeId));
        return WoniuBeanUtils.copyList(list, BatteryDto.class);
    }


}
